#!/usr/bin/env python

from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.api import users
import logging
import vdb, parser, ui

class MainHandler(webapp.RequestHandler):
    def get(self):
        vdb.ns_set()
        text = ui.get_menu()
        self.response.out.write(ui.format_page('admin', text))

class ResetHandler(webapp.RequestHandler):
    def get(self):
        vdb.ns_set()
        vdb.msg_reset_parsed()
        self.redirect('/')

class ParseHandler(webapp.RequestHandler):
    def get(self):
        vdb.ns_set()
        list = vdb.msg_get_unparsed()
        for item in list[:100]:
            if item.parent_id > 0:
                vdb.msg_delete(item.key().id())
            else:
                records = parser.parse(item.body)
                if records[0][1] == 'common':
                    records = parser.parse(item.subject)
                vdb.msg_update_from(item, records[0])
                vdb.stat_update(item)
                if len(records) > 1:
                    for record in records[1:]:
                        rec = vdb.msg_create_from(item)
                        vdb.msg_update_from(rec, record)
                        vdb.stat_update(rec)
        self.redirect('/')

class ViewHandler(webapp.RequestHandler):
    def get(self):
        vdb.ns_set()
        text = ui.get_menu()
        pgstate = ui.parse_state(self.request.get('s'))
        namespaces = vdb.ns_get_all()
        for ns in namespaces:
            text += "<b>[%s]</b><br>\n" % ns.namespace_name
            q = vdb.msg_get_by_ns(ns.namespace_name)
#            q = q.filter('name !=', 'M').filter('name !=', 'F')
            list = []
            list.append(('id', 'pid', 'date', 'place', 'name',
                         'atag', 'amount', 'parsed'))
            for item in q:
                list.append((item.key().id(), item.parent_id, item.date, item.place, item.name,
                             item.atag, item.amount, item.parsed))
            text += ui.format_table(1, list, pgstate)
        self.response.out.write(ui.format_page('viewer', text))

class DoOperationHandler(webapp.RequestHandler):
    def post(self):
        vdb.ns_set()

        op = self.request.get('op')
        recalc = self.request.get('recalc')
        logging.info('op: %s, recalc: %s' % (op, recalc))

        if recalc == 'Recalculate':
            cat = self.request.get('cat')
            vdb.stat_recalc(cat)
            self.redirect('/')
            return

        if op == '--clear--':
            op = ''

        ids = self.request.get_all('sel')

        if op == '--delete--':
            for id in ids:
                vdb.msg_delete(int(id))
        elif op == '--parse--':
            for id in ids:
                msg = vdb.msg_get(int(id))
                if msg.parent_id > 0:
                    vdb.msg_delete(msg.key().id())
                    continue
                records = parser.parse(msg.body)
                if records[0][1] == 'common':
                   records = parser.parse(msg.subject)
                logging.info('id: %s, record: %s' % (id, records[0]))
                vdb.msg_update_from(msg, records[0])
                vdb.stat_update(msg)
                for record in records[1:]:
                    rec = vdb.msg_clone(msg)
                    vdb.msg_update_from(rec, record)
                    logging.info('id: %d, record: %s' % (rec.key().id(), record))
                    vdb.stat_update(rec)
        else:
            for id in ids:
                vdb.msg_set_category(int(id), op)
        self.redirect('/')

def main():
    application = webapp.WSGIApplication([
        ('/admin/', MainHandler),
        ('/admin/view', ViewHandler),
        ('/admin/reset', ResetHandler),
        ('/admin/op', DoOperationHandler),
        ('/admin/parse', ParseHandler)],
        debug=True)
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
